﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Linq;

namespace DNA.Mvc
{
    /// <summary>
    /// Define the helper methods that use to convert the instances between template and data model instance.
    /// </summary>
    public static class TemplateConverter
    {
        public static Web Import(this IDataContext dbContext, WebTemplate template, string name, string owner)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            var thisWeb = dbContext.Webs.GetByName(name);

            if (thisWeb == null)
            {
                thisWeb = new Web()
               {
                   Name = name,
                   Owner = string.IsNullOrEmpty(owner) ? name : owner,
                   Created = DateTime.UtcNow,
                   DefaultLanguage = template.Language,
                   Copyright = string.IsNullOrEmpty(template.Copyright) ? "" : template.Copyright,
                   CssText = string.IsNullOrEmpty(template.CssText) ? "" : template.CssText,
                   LogoImageUrl = string.IsNullOrEmpty(template.LogoImageUrl) ? "" : template.LogoImageUrl,
                   DefaultUrl = string.IsNullOrEmpty(template.DefaultUrl) ? "" : template.DefaultUrl,
                   MasterName = string.IsNullOrEmpty(template.MasterPage) ? "" : template.MasterPage,
                   ShortcutIconUrl = string.IsNullOrEmpty(template.ShortcutIconUrl) ? "" : template.ShortcutIconUrl,
                   SearchKeywords = string.IsNullOrEmpty(template.SearchKeywords) ? "" : template.SearchKeywords,
                   MostOnlined = DateTime.UtcNow,
                   MostOnlineUserCount = 1,
                   MaximumFileSize = 2,
                   Type = name.Equals("home") ? (int)WebTypes.Public : (int)template.Type,
                   IsEnabled = true,
                   Title = template.Title,
                   Description = template.Description,
                   EnableUserRegistration = template.EnableUserRegistation,
                   AllowExtensions = ".doc|.docx|.txt|.jpg|.gif|.png|.zip|.rar|.xls|.xlsx|.ppt|.pptx",
                   Theme = template.Theme
               };
                thisWeb = dbContext.Webs.Create(thisWeb);
                dbContext.SaveChanges();
            }

            foreach (var wpTmpl in template.WebPages)
                dbContext.Import(thisWeb, wpTmpl);

            return thisWeb;
        }

        public static WebPage Import(this IDataContext dbContext, Web parentWeb, WebPageTemplate webPageTemplate, int parentWebPageID = 0)
        {
            var webName = parentWeb.Name;

            if ((webPageTemplate == null) || string.IsNullOrEmpty(webPageTemplate.Path))
                return null;

            if (webName.Equals("home"))
            {
                var defaultPath = string.Format("~/sites/{0}/index.html", webName).ToLower();
                var _path = webPageTemplate.Path.ToLower();

                ///NOTES:When the web site is top site and the webpage is addressed to home then set path to /home
                if (defaultPath.Equals(_path))
                {
                    webPageTemplate.Path = "~/home/index";
                    if (parentWeb.DefaultUrl.Equals(defaultPath))
                        parentWeb.DefaultUrl = "";
                    webPageTemplate.IsStatic = true;
                }
                else
                    webPageTemplate.IsStatic = false;
            }

            WebPage thisPage = dbContext.WebPages.Find(webPageTemplate.Path);

            if (thisPage == null)
            {
                thisPage = dbContext.WebPages.Create(parentWeb, parentWebPageID, webPageTemplate);
            }
            else
            {
                thisPage.From(webPageTemplate);
            }

            dbContext.SaveChanges();

            if (webPageTemplate.Widgets != null)
            {
                if (webPageTemplate.Widgets.Count > 0)
                {
                    var groupWidgets = webPageTemplate.Widgets.GroupBy(w => w.Defaults.ZoneID);

                    foreach (var orderedTmpl in groupWidgets)
                    {
                        var orderedWidgets = orderedTmpl.OrderBy(o => o.Defaults.Position);
                        foreach (var widgetTmpl in orderedWidgets)
                        {
                            dbContext.Import(thisPage, widgetTmpl);
                        }
                    }
                    dbContext.SaveChanges();
                }
            }

            if (webPageTemplate.Children != null)
            {
                foreach (var child in webPageTemplate.Children)
                    dbContext.Import(parentWeb, child, thisPage.ID);
            }

            return thisPage;
        }

        public static WidgetInstance Import(this IDataContext dbContext, WebPage parentPage, WidgetDescriptor descriptor, string zoneID = "zone0", int pos = 0)
        {
            return dbContext.Widgets.AddWidget(Guid.NewGuid(), descriptor, parentPage.Path, zoneID, pos);
        }

        public static WidgetInstance Import(this IDataContext dbContext, WebPage parentPage, WidgetTemplate widgetTemplate)
        {
            return dbContext.Widgets.AddWidget(Guid.NewGuid(), widgetTemplate, parentPage.Path, string.IsNullOrEmpty(widgetTemplate.Defaults.ZoneID) ? "zone0" : widgetTemplate.Defaults.ZoneID, widgetTemplate.Defaults.Position);
        }


    }
}
